package org.liubility.robot;

import net.mamoe.mirai.contact.Contact;
import net.mamoe.mirai.event.EventHandler;
import net.mamoe.mirai.event.SimpleListenerHost;
import net.mamoe.mirai.message.FriendMessageEvent;
import net.mamoe.mirai.message.GroupMessageEvent;
import net.mamoe.mirai.message.MessageEvent;
import net.mamoe.mirai.message.data.MessageChain;
import org.liubility.api.Api;
import org.liubility.pojo.dto.RobotMsgResult;
import org.liubility.pojo.entity.RobotPostOrder;

import java.util.List;

/**
 * @Author: Jdragon
 * @email: 1061917196@qq.com
 * @Date: 2020.09.04 12:47
 * @Description:
 */
public class PostOrderManage extends SimpleListenerHost {

    List<RobotPostOrder> postOrderList = Api.getPostOrder();

    @EventHandler
    public void handlePostOrder(GroupMessageEvent event) {
        handlePostOrder(event, MessageType.GROUP.getMode());
    }

    @EventHandler
    public void handlePostOrder(FriendMessageEvent event) {
        handlePostOrder(event, MessageType.FRIEND.getMode());
    }

    private void handlePostOrder(MessageEvent event, int model) {
        MessageChain chain = event.getMessage();
        String message = chain.contentToString();
        Contact subject = event.getSubject();
        if ("#刷新指令".equals(message)) {
            postOrderList = Api.getPostOrder();
            subject.sendMessage("刷新成功");
            return;
        }
        String[] s = message.split(" ");
        for (RobotPostOrder robotPostOrder : postOrderList) {
            int mode = robotPostOrder.getMode();
            if (mode != model && mode != 0) continue;
            if (!s[0].equals(robotPostOrder.getOrder())) continue;
            RobotMsgResult result = Api.robotHandle(robotPostOrder.getUrl(), robotPostOrder.getRequest(), robotPostOrder.getParam(), unpackMessage(event, s[1]));
            subject.sendMessage(result.getMessage());
        }
    }

    private RobotMsgResult unpackMessage(MessageEvent event, String message) {
        return RobotMsgResult.builder()
                .message(message)
                .senderId(event.getSender().getId()).build();
    }
}
